package cn.icast.netty.c5;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class TCPClient {
    public static void main(String[] args) throws InterruptedException {
        new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                      ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                          @Override
                          public void channelActive(ChannelHandlerContext ctx) throws Exception {
                              ByteBuf buffer = ctx.alloc().buffer(10);

                              buffer.writeBytes("hello".getBytes());
                              ctx.writeAndFlush(buffer);

                               buffer.release();

                          }
                      });
                      ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                          @Override
                          public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                              ByteBuf buf = msg instanceof ByteBuf ? (ByteBuf) msg : null;
                              System.out.println(buf.toString(Charset.defaultCharset()));
                              buf.release();
                          }
                      });
                    }
                }).connect(new InetSocketAddress("localhost",8080))
                .sync()
                .channel();



    }
}
